import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import MainLayout from '../../../components/MainLayout';
import PageHeader from './components/PageHeader';
import ManageTabs from './components/ManageTabs';
import NetworkOverview from './components/NetworkOverview';
import LoadingView from './components/LoadingView';
import ErrorView from './components/ErrorView';
import networkService from '../../../services/network';
import Toast from '../../../components/Toast';
import './NetworkManage.css';

const NetworkManage = () => {
  const { networkId } = useParams();
  const navigate = useNavigate();
  const [network, setNetwork] = useState(null);
  const [rules, setRules] = useState(null);
  const [userRole, setUserRole] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [basicSubmitting, setBasicSubmitting] = useState(false);
  const [rulesSubmitting, setRulesSubmitting] = useState(false);
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');

  // 获取网络数据
  const fetchNetworkData = async () => {

    
    try {
      setIsLoading(true);
      
      // 并行请求网络详情、用户角色和规则
      const [networkDetail, roleInfo, rulesResponse] = await Promise.all([
        networkService.getNetworkDetail(networkId),
        networkService.getUserNetworkRole(networkId),
        networkService.getNetworkRules(networkId).catch(() => ({ data: { code: 404 } }))
      ]);

      

      if (networkDetail.data.code === 200) {
        setNetwork(networkDetail.data.data);
      } else {
        showToastMessage('获取网络信息失败');
        return;
      }

      if (roleInfo.data.code === 200) {
        setUserRole(roleInfo.data.data.role);
        if (roleInfo.data.data.role !== 'admin') {
          showToastMessage('只有管理员可以访问此页面');
          navigate(`/network/${networkId}`);
          return;
        }
      } else {
        showToastMessage('您没有权限访问此页面');
        navigate(`/network/${networkId}`);
        return;
      }

      if (rulesResponse.data.code === 200) {
        setRules(rulesResponse.data.data);
      }
    } catch (err) {
      showToastMessage('获取网络信息失败，请稍后重试');
    } finally {
      setIsLoading(false);
    }
  };

  // 更新基本信息
  const handleBasicSubmit = async (values) => {
    try {
      setBasicSubmitting(true);
      const response = await networkService.updateNetwork(networkId, values);
      
      if (response.data.code === 200) {
        showToastMessage('网络信息更新成功');
        setNetwork(prev => ({ ...prev, ...values }));
      } else {
        showToastMessage(response.data.message || '更新失败，请稍后重试');
      }
    } catch (err) {
      showToastMessage(err.response?.data?.message || '更新失败，请稍后重试');
    } finally {
      setBasicSubmitting(false);
    }
  };

  // 更新规则配置
  const handleRulesSubmit = async (values) => {
    try {
      setRulesSubmitting(true);
      const response = await networkService.updateNetworkRules(networkId, values);
      
      if (response.data.code === 200) {
        showToastMessage('网络规则更新成功');
        setRules(prev => ({ ...prev, ...values, updatedAt: new Date().toISOString() }));
      } else {
        showToastMessage(response.data.message || '规则更新失败，请稍后重试');
      }
    } catch (err) {
      showToastMessage(err.response?.data?.message || '规则更新失败，请稍后重试');
    } finally {
      setRulesSubmitting(false);
    }
  };

  const showToastMessage = (message) => {
    setToastMessage(message);
    setShowToast(true);
  };

  // 初始化数据
  useEffect(() => {
    fetchNetworkData();
  }, [networkId]);

  // 加载状态
  if (isLoading) {
    return (
      <MainLayout>
        <LoadingView />
      </MainLayout>
    );
  }

  // 错误状态
  if (!network || userRole !== 'admin') {
    return (
      <MainLayout>
        <ErrorView 
          error="未找到网络信息或权限不足"
          onBack={() => navigate('/network')}
        />
      </MainLayout>
    );
  }

  return (
    <MainLayout>
      <div className="network-manage-container">
        <div className="network-manage-content">
          {/* 页面头部 */}
          <PageHeader 
            network={network}
            onRefresh={fetchNetworkData}
            isLoading={isLoading}
          />

          {/* 管理标签页 */}
          <ManageTabs
            network={network}
            rules={rules}
            basicSubmitting={basicSubmitting}
            rulesSubmitting={rulesSubmitting}
            onBasicSubmit={handleBasicSubmit}
            onRulesSubmit={handleRulesSubmit}
          />

          {/* 网络概览 */}
          <NetworkOverview network={network} />
        </div>
      </div>
      {showToast && (
        <Toast 
          message={toastMessage} 
          onClose={() => setShowToast(false)} 
        />
      )}
    </MainLayout>
  );
};

export default NetworkManage;